import React, { useState, useRef, useEffect } from 'react';
import { Input } from 'antd';
import styles from './index.less';

const HighlightedTextArea = ({ value, onChange }) => {
  const divRef = useRef(null);
  const [cursor, setCursor] = useState(null);
  // 需要高亮的关键词列表
  const highlightWords = ['重要', '紧急', 'TODO'];
  // 高亮逻辑
  // const highlightContent = (text) => {
  //   return text.replace(`(${highlightWords.join('|')})`
  //     /(TODO|FIXME)/g,
  //     '<span class="highlight">$1</span>'
  //   );
  // };

  const highlightContent = (text) => {
    const regex = new RegExp(`(${highlightWords.join('|')})`, 'gi');
    if (text) {
      return text.replace(
        regex,
        '<span class="highlight" style="background-color: yellow;">$1</span>',
      );
      // return highlightWords.reduce((acc, cur) => {
      //   console.log(acc, cur);
      //   return acc.replace(regex, '<span class="highlight" style="background-color: yellow;">$1</span>')
      // }, text);
    } else {
      return '';
    }

    // return text.replace(regex, '<mark class="highlight">$1</mark>');
  };

  // 同步内容到父组件
  const handleInput = (e) => {
    const newValue = e.target.innerHTML;
    onChange(newValue.replace(/<\/?[^>]+(>|$)/g, '')); // 剥离HTML标签后传值
  };

  // 处理光标位置
  const handleBlur = () => {
    const sel = window.getSelection();
    if (sel.rangeCount > 0) {
      const range = sel.getRangeAt(0);
      setCursor(range.cloneRange());
    }
  };

  // 恢复光标
  useEffect(() => {
    if (cursor && divRef.current) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(cursor);
    }
  }, [value, cursor]);

  return (
    <div
      ref={divRef}
      className="ant-input editable-area"
      contentEditable
      dangerouslySetInnerHTML={{ __html: highlightContent(value) }}
      onInput={handleInput}
      onBlur={handleBlur}
      placeholder="请输入内容..."
    />
  );
};

export default HighlightedTextArea;
